package com.wtwd.campus.controller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.xiaoymin.knife4j.annotations.DynamicParameter;
import com.github.xiaoymin.knife4j.annotations.DynamicParameters;
import com.wtwd.campus.annotation.AuditLog;
import com.wtwd.campus.common.RespCode;
import com.wtwd.campus.constant.SignConstant;
import com.wtwd.campus.entity.School;
import com.wtwd.campus.entity.SysUser;
import com.wtwd.campus.entity.Teacher;
import com.wtwd.campus.model.TeacherExcelImportModel;
import com.wtwd.campus.model.TeacherQueryModel;
import com.wtwd.campus.model.vo.ImportExcelResponseVO;
import com.wtwd.campus.model.vo.PageDataVO;
import com.wtwd.campus.model.vo.ResultVO;
import com.wtwd.campus.model.vo.TeacherVO;
import com.wtwd.campus.service.*;
import com.wtwd.campus.utils.AuditLogUtils;
import com.wtwd.campus.utils.ExcelUtils;
import com.wtwd.campus.utils.MyExcelUtils;
import io.swagger.annotations.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.lang.reflect.Method;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author zdl
 * @since 2021-07-08
 */
@Api(tags = "教师管理")
@RestController
@RequestMapping("/teacher")
public class TeacherController {

    @Resource
    private SysUserService sysUserService;

    @Resource
    private TeacherService teacherService;

    @Resource
    private SchoolService schoolService;

    @Autowired
    private LogService logService;

    @Resource
    private ClassService classService;

    @ApiOperation(value = "查询教师分页数据", notes = "")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNo", value = "页数", required = true, dataTypeClass = Integer.class)
            , @ApiImplicitParam(name = "pageSize", value = "页大小", required = true, dataTypeClass = Integer.class)
    })
    @GetMapping("/page")
    public ResultVO<PageDataVO<TeacherVO>> queryPage(@RequestParam(defaultValue = "1") Integer pageNo
            , @RequestParam(defaultValue = "10") Integer pageSize, TeacherQueryModel teacherQueryModel) {
        Page<TeacherVO> page = new Page<>(pageNo, pageSize);
        SysUser user = sysUserService.getCurrentLoginUser();
        List<Integer> schoolIds = null;
        Integer schoolId = teacherQueryModel.getSchoolId();
        if (schoolId == null) {
            List<School> schools = schoolService.getSchoolByOrgCode(user.getOrgCode());
            schoolIds = schools.stream().map(School::getId).collect(Collectors.toList());
        } else {
            schoolIds = new ArrayList<>();
            schoolIds.add(schoolId);
        }
        teacherQueryModel.setSchoolIds(schoolIds);
        IPage<TeacherVO> dataPage = teacherService.queryPage(page, teacherQueryModel);
        //TODO 通过班级ID,获取班级名称及其年级名称
        List<TeacherVO> records = dataPage.getRecords();
        if (records.size() == 0) {
            return ResultVO.ok(dataPage);

        }
        StringBuffer classIds = new StringBuffer();
        records.forEach(item -> {
            if (item.getManageClass() != null) {
                classIds.append(SignConstant.COMMA).append(item.getManageClass());
            }
            classIds.append(SignConstant.COMMA).append(item.getTeachClass());
        });
        LinkedHashSet<String> list = new LinkedHashSet<>(Arrays.asList(classIds.substring(1).split(SignConstant.COMMA)));
        Map<Integer, String> classGradeName = classService.getClassGradeNameByClassIds(StringUtils.join(list, SignConstant.COMMA));
        records.forEach(item -> {
            String manageClass = classGradeName.get(item.getManageClass());
            if (StringUtils.isNotBlank(manageClass)) {
                item.setManageClassName(manageClass.substring(manageClass.indexOf(SignConstant.DELIMITER) + 1));
            }
            StringBuffer teachClassName = new StringBuffer();
            StringBuffer teachClass = new StringBuffer();
            for (String s : item.getTeachClass().split(SignConstant.COMMA)) {
                if (teachClassName.length() != 0) {
                    teachClassName.append(SignConstant.COMMA);
                    teachClass.append(SignConstant.COMMA);
                }
                String teachClassN = classGradeName.get(Integer.valueOf(s));
                if (StringUtils.isNotBlank(teachClassN)) {
                    teachClassName.append(teachClassN.substring(teachClassN.indexOf(SignConstant.DELIMITER) + 1));
                    teachClass.append(String.join(SignConstant.DELIMITER, teachClassN.substring(0, teachClassN.indexOf(SignConstant.DELIMITER)), s));
                }
            }
            item.setTeachClassName(teachClassName.toString());
            item.setTeachClass(teachClass.toString());
        });
        return ResultVO.ok(dataPage);
    }


    @ApiOperation("添加教师信息")
    @DynamicParameters(name = "addTeacherModel", properties = {
            @DynamicParameter(name = "schoolId", value = "学校ID", dataTypeClass = Integer.class, required = true)
            , @DynamicParameter(name = "name", value = "教师名称", dataTypeClass = String.class, required = true)
            , @DynamicParameter(name = "type", value = "教师类型", dataTypeClass = Integer.class, required = true, example = "1-班主任,2-授课老师")
            , @DynamicParameter(name = "manageClass", value = "管理班级ID", dataTypeClass = Integer.class, example = "教师类型为1时,必填")
            , @DynamicParameter(name = "manageClassGrade", value = "管理班级年级ID", dataTypeClass = Integer.class, example = "教师类型为1时,必填")
            , @DynamicParameter(name = "phone", value = "手机号", dataTypeClass = String.class, required = true)
            , @DynamicParameter(name = "teachClass", value = "授课班级ids", dataTypeClass = String.class, required = true, example = "1,2,3")
            , @DynamicParameter(name = "teachClassGrade", value = "授课班级年级ids", dataTypeClass = String.class, required = true, example = "1,2,3")
    })
    @ApiResponses({@ApiResponse(code = 400, message = "参数错误")
            , @ApiResponse(code = 1104, message = "该教师分配的班级已经存在班主任")
            , @ApiResponse(code = 700, message = "号码已存在")
    })
    @PostMapping("/teacherInfo")
    @AuditLog(operationType = "添加教师信息", operationContent = "", orgCode = "")
    public ResultVO add(@RequestBody JSONObject addTeacherModel) {
        Teacher classes = JSONObject.toJavaObject(addTeacherModel, Teacher.class);
        ResultVO resultVO = teacherService.createTeacher(classes);
        if (resultVO.getCode() == RespCode.SUCCESS.getCode()) {
            Method method = null;
            try {
                method = TeacherController.class.getMethod("add", JSONObject.class);
                //获取操作的组织的code
                Integer schoolId = (Integer) addTeacherModel.get("schoolId");
                School school = logService.getSchoolById(schoolId);
                String orgCode = school.getOrgCode();
                String operationContent = "添加教师信息：".concat((String) addTeacherModel.get("name"));
                AuditLogUtils.modifyAnnotation(method, operationContent, orgCode);
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            }
        }
        return resultVO;
    }


    @ApiOperation("更新教师信息")
    @ApiResponses({@ApiResponse(code = 400, message = "参数错误")
            , @ApiResponse(code = 1104, message = "该教师分配的班级已经存在班主任")
            , @ApiResponse(code = 700, message = "号码已存在")
    })
    @DynamicParameters(name = "updateTeacherModel", properties = {
            @DynamicParameter(name = "id", value = "教师ID", dataTypeClass = String.class, required = true)
            , @DynamicParameter(name = "name", value = "教师名称", dataTypeClass = String.class)
            , @DynamicParameter(name = "type", value = "教师类型", dataTypeClass = Integer.class, example = "1-班主任,2-授课老师")
            , @DynamicParameter(name = "manageClass", value = "管理班级ID", dataTypeClass = Integer.class, example = "教师类型为1时,必填")
            , @DynamicParameter(name = "manageClassGrade", value = "管理班级年级ID", dataTypeClass = Integer.class, example = "教师类型为1时,必填")
            , @DynamicParameter(name = "phone", value = "手机号", dataTypeClass = String.class)
            , @DynamicParameter(name = "teachClass", value = "授课班级ids", dataTypeClass = String.class, example = "1,2,3")
            , @DynamicParameter(name = "teachClassGrade", value = "授课班级年级ids", dataTypeClass = String.class, example = "1,2,3")
    })
    @PutMapping("/teacherInfo")
    @AuditLog(operationType = "更新教师信息", operationContent = "", orgCode = "")
    public ResultVO update(@RequestBody JSONObject updateTeacherModel) {
        Teacher classes = JSONObject.toJavaObject(updateTeacherModel, Teacher.class);
        //根据教师id拿到修改前教师姓名和所属组织code
        Map<String, Object> map = logService.getTeacherNameAndSchoolCodeById(classes.getId());
        ResultVO resultVO = teacherService.updateTeacher(classes);
        //添加操作日志
        if (resultVO.getCode() == RespCode.SUCCESS.getCode()) {
            Method method = null;
            try {
                method = TeacherController.class.getMethod("update", JSONObject.class);
                //获取操作的组织的code
                String orgCode = (String) map.get("org_code");
                String name = (String) map.get("name");
                String operationContent = "";
                if (!classes.getName().equals(name)) {
                    operationContent = name.concat("更改为").concat(classes.getName());
                } else {
                    operationContent = "修改".concat("name").concat("教师信息");
                }
                AuditLogUtils.modifyAnnotation(method, operationContent, orgCode);
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            }
        }
        return resultVO;
    }

    @ApiOperation("删除教师信息")
    @ApiImplicitParam(name = "id", value = "教师id", required = true, dataTypeClass = Integer.class, paramType = "path")
    @DeleteMapping("/teacherInfo/{id}")
    @AuditLog(operationType = "删除教师信息", operationContent = "", orgCode = "")
    public ResultVO delete(@PathVariable Integer id) {
        //根据教师id拿到修改前教师姓名和所属组织code
        Map<String, Object> map = logService.getTeacherNameAndSchoolCodeById(id);
        ResultVO resultVO = teacherService.deleteTeacherById(id);
        //添加操作日志
        if (resultVO.getCode() == RespCode.SUCCESS.getCode()) {
            Method method = null;
            try {
                method = TeacherController.class.getMethod("delete", Integer.class);
                //获取操作的组织的code
                String orgCode = (String) map.get("org_code");
                String name = (String) map.get("name");
                String operationContent = "删除教师：".concat(name);
                AuditLogUtils.modifyAnnotation(method, operationContent, orgCode);
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            }
        }
        return resultVO;
    }

    @ApiOperation("导入教师")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "file", value = "文件", required = true, dataTypeClass = MultipartFile.class)
            , @ApiImplicitParam(name = "schoolId", value = "学校ID", required = true, dataTypeClass = Integer.class)
    })
    @ApiResponses({@ApiResponse(code = 400, message = "请求参数错误"),
            @ApiResponse(code = 801, message = "文件格式错误")
    })
    @PostMapping("teacherInfo/excel")
    @AuditLog(operationType = "批量导入教师", operationContent = "", orgCode = "")
    public ResultVO importByExcel(@RequestBody MultipartFile file, @RequestParam Integer schoolId) {
        try {
            String fileName = file.getOriginalFilename();
            if (!ExcelUtils.validateExcel(fileName)) {
                return ResultVO.error(RespCode.FILE_FORMAT_ERROR);
            }
            List<TeacherExcelImportModel> teacherExcelImportModels = MyExcelUtils.importExcel(file, 1, 1, TeacherExcelImportModel.class);
            ResultVO resultVO = teacherService.importByExcel(schoolId, teacherExcelImportModels);
            //添加操作日志
            if (resultVO.getCode() == RespCode.SUCCESS.getCode()) {
                Method method = null;
                try {
                    method = TeacherController.class.getMethod("importByExcel", MultipartFile.class, Integer.class);
                    //获取操作的组织的code
                    School school = logService.getSchoolById(schoolId);
                    Object data = resultVO.getData();
                    long num = 0;
                    if (data != null) {
                        ImportExcelResponseVO map = (ImportExcelResponseVO) data;
                        num = map.getSuccessNum();
                    }
                    String operationContent = "导入".concat(String.valueOf(num)).concat("条教师信息");
                    AuditLogUtils.modifyAnnotation(method, operationContent, school.getOrgCode());
                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                }
            }
            return resultVO;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResultVO.error(RespCode.FILE_FORMAT_ERROR);
    }

}

